const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const bCrypt = require('bcryptjs')

//接收两个参数-work_number/password
router.post('/register', async (req, res) => {
    // console.log(req.body.email.length)
    // console.log(req.body.username.length)
    // console.log(req.body.password.length)
    //判断邮箱是否符合格式
    if (req.body.email.length<0||req.body.email.length>100
        ||req.body.username.length>15||req.body.username.length<3
        ||req.body.password.length>20||req.body.password.length<6
        ||req.body.true_name.length>15||req.body.true_name.length<3) {
        res.json({
            'code': 400,
            'result': 'false',
            'type': 'format_error',
            'content': '语法错误，输入表单格式不正确'
        })
        return
    }
    else{
        //加密密码
        const salt = bCrypt.genSaltSync(10)
        const data = {
            username: req.body.username,
            true_name: req.body.true_name,
            password: bCrypt.hashSync(req.body.password,salt),
            email: req.body.email
        }
        //判断邮箱是否已经注册
        let sql = 'select * from user where email = ?'
        db.base(sql, data.email, response => {
            if (response.length > 0){
                res.json({
                    'code': 403,
                    'result': 'false',
                    'type': 'email_exist',
                    'content': '拒绝执行该请求，邮箱已经存在'
                })
                return
            }
            else {
                //判断数据库中是否存在该用户
                let sql = 'select * from user where username = ?'
                db.base(sql, data.username, response => {
                    //    如果注册用户名已经存在，则返回
                    if(response.length > 0){
                        res.json({
                            'code': 403,
                            'result': 'false',
                            'type': 'username_exist',
                            'content': '拒绝执行该请求，用户名已经存在'
                        })
                        return
                    }
                    else {
                        let sql = 'insert into user set ?'
                        db.base(sql, data, () => {
                            res.json({
                                'code': 200,
                                'result': 'true',
                                'type': 'success',
                                'content': '成功注册'
                            })
                            return
                        })
                    }

                })
            }
        })
    }
})

module.exports = router
